package cn.tedu.v4;


import java.io.*;
import java.net.ConnectException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

/**
 * Client 客户端--改成Server 端模式 【优化】
 */
public class Client {
    private Socket socket;
    private static final  Integer PORT=4545 ;
    private static final  String HOST="127.0.0.1";
    private BufferedReader br;
    private PrintWriter pw;

    public Client() {
        try {
            socket = new Socket(HOST, PORT);
            pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8")), true);
            br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF8"));
        } catch (NullPointerException e) {
            System.out.println("友情提示：IP传入错误导致连接失败~");
        } catch (UnknownHostException e) {
            System.out.println("友情提示：IP传入出错");
        } catch (ConnectException e) {
            System.out.println("客户端连接失败：建议检查IP/端口号");
        } catch (IOException e) {
            System.out.println("客户端连接服务器端失败了，提示：检查IP/端口");
        }
    }

    public void start() {
        try {


            new Thread(() -> {
                try {

                    String message;
                    //br.readLine()读取一行
                    while ((message = br.readLine()) != null) {
                        System.out.println("服务器端说：" + message);
                        System.out.println("客户端请输入:");
                    }
                } catch (IOException e) {
                    System.out.println("服务器端读入失败");
                }
            }).start();

            Scanner input = new Scanner(System.in);
            while (true) {
                System.out.println("客户端请输入：");
                String line = input.nextLine();
                pw.println("客户端说：" + line);//发给服务器

            }
        } finally {
            if (pw!= null)
                pw.close();
            if (br!=null)
                try {
                    br.close();
                } catch (IOException e) {
                    System.out.println("客户端关闭失败");
                }
            if (socket != null && !socket.isClosed()) {
                try {
                    socket.close();
                } catch (IOException e) {
                    System.out.println("通讯关闭失败~");
                }
            }
        }
    }

    public static void main(String[] args) {
        new Client().start();
    }

    private class ClientHandler implements Runnable {
        private Socket socket;
        private String ip;

        public ClientHandler(Socket s) {
            this.socket = s;
            ip = socket.getInetAddress().getHostAddress();
        }
        public void run() {

        }
    }
}